#include <QCoreApplication>
#include <QHostAddress>
#include <QNetworkInterface>
#include <QUdpSocket>
#include <QTextCodec>
#include <thread>

inline QTextCodec *GetGbkTextCodec()
{
	static QTextCodec *spTextCodec = QTextCodec::codecForName("GB18030");
	return spTextCodec;
}

inline QString tr2(const char *lpszText)
{
	return GetGbkTextCodec()->toUnicode(lpszText);
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	QString strMulticastNetworkName = tr2("wlo1");
	int nIndex = 0;
	const QList<QNetworkInterface> &lni = QNetworkInterface::allInterfaces();
	for (int i = 0; i < lni.size(); i++)
	{
		if (lni[i].humanReadableName().indexOf(strMulticastNetworkName) >= 0)
		{
			nIndex = i;
			break;
		}
	}

	QHostAddress groupAddr("234.5.6.7");
	for (int i = 8888; i < 8898; i++)
	{
		QUdpSocket *udp = new QUdpSocket;
		bool b = udp->bind(QHostAddress::AnyIPv4, i);// , QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
//		b = udp->joinMulticastGroup(groupAddr, lni[nIndex]);
 		b = udp->joinMulticastGroup(groupAddr);
		QObject::connect(udp,
			&QUdpSocket::readyRead,
			[udp, &i]()
		{
			while (udp->hasPendingDatagrams())
			{
				QByteArray datagram;
				datagram.resize(udp->pendingDatagramSize());
				udp->readDatagram(datagram.data(), datagram.size());
				printf("%s\n", datagram.data());
			}
		});
	}
	a.exec();

#ifdef WIN32
// 	WSACleanup();
#endif
	return 0;
}
